//
//  TZHGInteractViewController.m
//  AnXin100
//
//  Created by 王合润 on 2018/9/17.
//  Copyright © 2018年 tzhg. All rights reserved.
//

#import "TZHGInteractViewController.h"
#import <ZFPlayer/ZFPlayer.h>
#import "ZFAVPlayerManager.h"
#import "ZFIJKPlayerManager.h"
#import "KSMediaPlayerManager.h"
#import "ZFPlayerControlView.h"
#import "ZFTableViewCellLayout.h"
#import "ZFTableData.h"
#import "ZFTableViewCell.h"
#import "InteractHomeTableViewCell.h"
#import "OfficialMediaViewController.h"
#import "EnterpriseDynamicViewController.h"
#import "AboutUsViewController.h"
#import "InBrandViewController.h"
#import "BaseSourceViewController.h"
#import "EvaluateStatisticsViewController.h"
#import "AXUrlLogin.h"
#import "AXUrlListPartC.h"
@interface TZHGInteractViewController ()<UITableViewDelegate, UITableViewDataSource, ZFTableViewCellDelegate>

@property (nonatomic ,strong) UIButton *searchButton;

@property (nonatomic, strong) UITableView *mainTable;

@property (nonatomic, strong) ZFPlayerController *player;

@property (nonatomic, strong) ZFPlayerControlView *controlView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSDictionary *dicData;

@property (nonatomic, strong) NSMutableArray *arrayModel;
@end

@implementation TZHGInteractViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupNavigationItems];
    [self.view addSubview:self.mainTable];
    [self getViedoData];
    [self getSecondPageData];
    
    /// playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    /// player,tag值必须在cell里设置
    self.player = [ZFPlayerController playerWithScrollView:self.mainTable playerManager:playerManager containerViewTag:100];
    self.player.controlView = self.controlView;
    /// 0.8是消失80%时候
    self.player.playerDisapperaPercent = 0.8;
    
    @weakify(self)
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        [self.player stopCurrentPlayingCell];
    };
    
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        [UIViewController attemptRotationToDeviceOrientation];
        self.mainTable.scrollsToTop = !isFullScreen;
    };
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat h = CGRectGetMaxY(self.view.frame);
    self.mainTable.frame = CGRectMake(0, y, self.view.frame.size.width, h- y - 49);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setupNavigationItems {
    //客服按钮
    UIButton *kfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    kfBtn.layer.cornerRadius = 3;
    kfBtn.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    [kfBtn setImage:[UIImage imageNamed:@"navkf"] forState:UIControlStateNormal];
    kfBtn.frame = CGRectMake(0, 0, 60, 30);
    [kfBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
//    [kfBtn addTarget:self action:@selector(kfAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:kfBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    /** 搜索 */
    self.searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-140, 30)];
    self.searchButton.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    self.searchButton.titleLabel.font = FONT_TWELVE;
//    [self.searchButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    [self.searchButton setTitleColor:[UIColor colorWithHex:0x29b566] forState:UIControlStateNormal];
    [self.searchButton setTitle:@"安心100直营店" forState:UIControlStateNormal];
    self.searchButton.cornerRadius = 3;
    [self.searchButton setImage:[UIImage imageNamed:@"ss"] forState:UIControlStateNormal];
    self.navigationItem.titleView = self.searchButton;
}



// 懒加载
- (UITableView *)mainTable {
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_mainTable registerClass:[ZFTableViewCell class] forCellReuseIdentifier:@"ZFTableViewCell"];
        [_mainTable registerClass:[InteractHomeTableViewCell class] forCellReuseIdentifier:@"InteractHomeTableViewCell"];
        
        _mainTable.delegate = self;
        _mainTable.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _mainTable.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTable.estimatedRowHeight = 0;
        _mainTable.estimatedSectionFooterHeight = 0;
        _mainTable.estimatedSectionHeaderHeight = 0;
    }
    return _mainTable;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
    }
    return _controlView;
}

// 播放器
- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}
#pragma mark - UIScrollViewDelegate   列表播放必须实现

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidEndDecelerating];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScroll];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewWillBeginDragging];
}

#pragma mark - UITabelView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        return 150;
    } else {
        
        if (indexPath.row == 0) {
            ZFTableViewCellLayout *layout = self.dataSource[indexPath.row];
            return layout.height;
        } else {
            ZFTableViewCellLayout *layout = self.dataSource[indexPath.row - 1];
            return layout.height;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        
        ZX_WEAK_SELF
        InteractHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InteractHomeTableViewCell"];
        cell.btnClick = ^(NSInteger i) {
            if (i == 0) {
                OfficialMediaViewController *vc = [[OfficialMediaViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.demoId = weakSelf.dicData[@"demoId"];
                [self.navigationController pushViewController:vc animated:YES];

            } else if (i == 1) {

                BaseSourceViewController *vc = [BaseSourceViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
                
            } else {
                
                BaseSourceViewController *vc = [BaseSourceViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else {

        ZFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZFTableViewCell"];
        [cell setDelegate:self withIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.layout = self.dataSource[indexPath.row];
        } else {
            cell.layout = self.dataSource[indexPath.row - 1];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setNormalMode];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        
    } else {
        if (self.player.playingIndexPath != indexPath) {
            [self.player stopCurrentPlayingCell];
        }
    }
    
}

#pragma mark - ZFTableViewCellDelegate
- (void)zf_playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    
    [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
}
#pragma mark - private method
/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    
    ZFTableViewCellLayout *layout = nil;
    if (indexPath.row == 0) {
        layout = self.dataSource[indexPath.row];
    } else {
        layout = self.dataSource[indexPath.row - 1];
    }
    [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:layout.data.fileUrl] scrollToTop:scrollToTop];
    [self.controlView showTitle:layout.data.title
                 coverURLString:layout.data.linkOrCover
                 fullScreenMode:layout.isVerticalVideo?ZFFullScreenModePortrait:ZFFullScreenModeLandscape];
}

#pragma mark - 获取数据
- (void)getSecondPageData {
    
    [NetWorkHelp yl_postDataWith:[NSMutableDictionary dictionaryWithDictionary:@{@"inModel" : @"hd"}] url:URL_SPLIT(URL_Interactive, URL_Interactive_QueryFirstMenu) success:^(id respose) {
        NSLog(@"%@", respose);
        _dicData = respose[@"body"][@"baseDemos"][0];
    } failure:^(NSError *error) {
        
    }];
}

- (void)getViedoData {
    
    [NetWorkHelp yl_postDataWith:@{@"location" : @"gfxcp"} url:URL_SPLIT(URL_Interactive, URL_Interactive_Viedo) success:^(id respose) {
        
        self.dataSource = @[].mutableCopy;
        for (NSDictionary *dataDic in respose[@"body"][@"picOrVideo"]) {
            ZFTableData *data = [[ZFTableData alloc] init];
            [data setValuesForKeysWithDictionary:dataDic];
            ZFTableViewCellLayout *layout = [[ZFTableViewCellLayout alloc] initWithData:data];
            [self.dataSource addObject:layout];
        }
        [_mainTable reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}

@end
